import { 
      ApplicationRef,
      Component,
      OnInit,
      Input,
      Output,
      Injectable,
      TemplateRef,
      ComponentFactoryResolver,
      ComponentFactory,
      ComponentRef,
      EmbeddedViewRef,
      ViewRef,
      EventEmitter,
      ElementRef 
      } from '@angular/core';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {
  
  @Input()title:string='';
  @Output()confirmBtn=new EventEmitter<any>();
  constructor(private elementRef:ElementRef) {  }

  ngOnInit() {

  }

  ngAfterContentChecked(){
    
  }
  close(){
  
   document.body.removeChild(this.elementRef.nativeElement);
    
  }

}
@Injectable()
export class ModalService{

    constructor(private resolver:ComponentFactoryResolver,private app:ApplicationRef){}
    /**
     * [open description]
     * @param {any}       content [description]
     * @param {(e)=>void} cb      [description]
     * @param {string}    title   [description]
     */
    open(content:any,cb:(e)=>void,title:string){
       let viewRef=content.createEmbeddedView(null);

           //模板被编译后再插入Modal组件中
           this.app.attachView(viewRef);
       let rootNodes = viewRef.rootNodes;
       let factory:ComponentFactory<ModalComponent> = this.resolver.resolveComponentFactory(ModalComponent);
        console.log(factory.inputs);
        console.log(factory.outputs);
       let modalRef:ComponentRef<ModalComponent> = factory.create(null,[rootNodes]);
          console.log(modalRef.instance);
          modalRef.instance.title=title;
           modalRef.instance.confirmBtn.subscribe(cb);
           modalRef.changeDetectorRef.detectChanges();
          // modalRef.hostView.detectChanges();
       window.document.body.appendChild(modalRef.location.nativeElement);
    }
	
}
